// SSE连接工具
export interface SSEOptions {
  onMessage: (data: string) => void;
  onError?: (error: Event) => void;
  onOpen?: (event: Event) => void;
  onClose?: () => void;
  onTimeout?: () => void;
}

export class SSEConnection {
  private eventSource: EventSource | null = null;
  private url: string;
  private options: SSEOptions;
  private isConnecting: boolean = false;
  private isClosed: boolean = false;
  private timeoutTimer: number | null = null;
  private readonly TIMEOUT_DURATION = 5 * 60 * 1000; // 5分钟

  constructor(url: string, options: SSEOptions) {
    this.url = url;
    this.options = options;
  }

  connect(): void {
    if (this.isConnecting || this.isConnected() || this.isClosed) {
      return;
    }

    if (this.eventSource) {
      this.disconnect();
    }

    this.isConnecting = true;
    this.isClosed = false;
    this.eventSource = new EventSource(this.url);

    this.eventSource.onopen = (event) => {
      this.isConnecting = false;
      console.log('SSE连接已建立');
      
      // 启动超时定时器
      this.startTimeoutTimer();
      
      this.options.onOpen?.(event);
    };

    this.eventSource.onmessage = (event) => {
      // 收到消息时重置超时定时器
      this.resetTimeoutTimer();
      this.options.onMessage(event.data);
    };

    this.eventSource.onerror = (error) => {
      this.isConnecting = false;
      console.log('SSE连接状态变化:', {
        readyState: this.eventSource?.readyState,
        error: error
      });
      
      // 检查是否是正常的流结束
      if (this.eventSource?.readyState === EventSource.CLOSED) {
        // 如果是正常关闭（流结束），不当作错误处理
        console.log('SSE流正常结束');
        this.isClosed = true;
        this.eventSource = null;
        this.options.onClose?.();
        return;
      }
      
      // 真正的连接错误处理
      console.error('SSE连接错误:', error);
      this.options.onError?.(error);
      this.disconnect();
    };
  }

  disconnect(): void {
    // 清除超时定时器
    this.clearTimeoutTimer();
    
    if (this.eventSource && !this.isClosed) {
      this.eventSource.close();
      this.eventSource = null;
      this.isConnecting = false;
      this.isClosed = true;
      this.options.onClose?.();
      console.log('SSE连接已关闭');
    } else if (this.eventSource) {
      // 如果已经关闭，只清理引用，不再调用onClose
      this.eventSource = null;
      this.isConnecting = false;
      console.log('SSE连接引用已清理');
    }
  }

  private startTimeoutTimer(): void {
    this.clearTimeoutTimer();
    this.timeoutTimer = setTimeout(() => {
      console.log('SSE连接超时 - 5分钟内未收到任何消息');
      this.handleTimeout();
    }, this.TIMEOUT_DURATION);
  }

  private resetTimeoutTimer(): void {
    this.startTimeoutTimer();
  }

  private clearTimeoutTimer(): void {
    if (this.timeoutTimer) {
      clearTimeout(this.timeoutTimer);
      this.timeoutTimer = null;
    }
  }

  private handleTimeout(): void {
    this.options.onTimeout?.();
    this.disconnect();
  }

  isConnected(): boolean {
    return this.eventSource !== null && this.eventSource.readyState === EventSource.OPEN;
  }

  getReadyState(): number {
    return this.eventSource?.readyState ?? EventSource.CLOSED;
  }
}

// 创建SSE连接的便捷函数
export function createSSEConnection(url: string, options: SSEOptions): SSEConnection {
  return new SSEConnection(url, options);
}

// 生成唯一的聊天会话ID
export function generateChatId(): string {
  return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 构建SSE URL
export function buildSSEUrl(endpoint: string, question: string, chatId: string): string {
  const baseUrl = 'http://localhost:6161/api';
  const params = new URLSearchParams({
    question: question,
    chatId: chatId
  });
  return `${baseUrl}${endpoint}?${params.toString()}`;
}